<?php

namespace app\api\controller\User;

use think\Controller;
use PHPMailer\PHPMailer\PHPMailer;
use think\Request;

class Base extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');
        $this->RecordModel = model('Record');
    }

    public function register()
    {
        $email = $this->request->param('email', '');
        $password = $this->request->param('password', '');

        //注册用积分
        $RegisterPoint = model('Config')->where('key', 'RegisterPoint')->value('value');

        $salt = build_ranstr();

        $password = md5($password . $salt);

        $data = [
            'email' => $email,
            'password' => $password,
            'salt' => $salt,
            'point' => $RegisterPoint,
            'sex' => 0,
            'auth' => 0,
            'vip' => 1,
        ];

        //插入数据库
        $result = $this->UserModel->Validate('common/User/User.vue')->save($data);

        if ($result == FALSE) {
            $this->error($this->UserModel->getError());
        } else {
            $this->success('注册成功', '/user/base/login');
        }
    }

    public function login()
    {
        $params = $this->request->param();
        //通过用户名去查询数据库是否存在该用户
        $User = $this->UserModel->where(['email' => $params['email']])->find();

        //查询出来的结果为空， 说明该用户不存在
        if (!$User) {
            $this->error('该用户不存在');
        }
        $password = md5($params['password'] . $User['salt']);

        if ($password != $User['password']) {
            $this->error('密码错误');
        }
        //设置cookie
        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'region' => $User['region_text'],
            'region_text' => $User['region_text'],
            'sign_time' => $User['sign_time'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
        ];
        // cookie('LoginUserBack', $data);
        $this->success('登录成功', '/user/base/index', $data);
    }

    //检查是否登录
    public function check()
    {
        $userid = $this->request->param('userid', 0);
        $User = $this->UserModel->where('id', $userid)->find();
        if (!$User) {
            $this->error('非法登录');
        } else {
            $data = [
                'id' => $User['id'],
                'email' => $User['email'],
                'nickname' => $User['nickname'],
                'avatar' => $User['avatar_cdn'],
                'cover' => $User['cover_cdn'],
                'sex' => $User['sex'],
                'sex_text' => $User['sex_text'],
                'region' => $User['region_text'],
                'sign_time' => $User['sign_time'],
                'province' => $User['province'],
                'city' => $User['city'],
                'district' => $User['district'],
                'createtime' => $User['createtime'],
                'content' => $User['content'],
                'point' => $User['point'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
            ];
            $this->success('登录成功', '/user/base/index', $data);
        }
    }

    //修改基本资料
    public function profile()
    {
        $params = $this->request->param();

        $user = $this->UserModel->find($params['id']);
        // halt($user);

        if (!$user) {
            $this->error('用户不存在');
        }

        // 封装数据
        $data = [
            'id' => $params['id'],
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'content' => $params['content']
        ];

        //地区的修改
        if (!empty($params['code'])) {
            $parentpath = model('Region')->where(['code' => $params['code']])->value('parentpath');

            if (!$parentpath) {
                $this->error('所选地区不存在');
            }
            $array = explode(',', $parentpath);
            $province = $array[0];
            $city = $array[1];
            $district = $array[2];
            // [$province, $city, $district] = 

            if ($province) {
                $data['province'] = $province;
            }

            if ($city) {
                $data['city'] = $city;
            }

            if ($district) {
                $data['district'] = $district;
            }
        }

        //密码的修改
        if (!empty($params['password'])) {
            // 密码盐
            $salt = build_ranstr();

            // 加密
            $data['password'] = md5($params['password'] . $salt);

            $data['salt'] = $salt;
        }

        //头像修改
        if (!empty($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
            $avatar = upload('avatar');

            if ($avatar['code'] == 0) {
                $this->error($avatar['msg']);
            }

            $data['avatar'] = $avatar['data'];
        }

        //背景修改
        if (!empty($_FILES['cover']) && $_FILES['cover']['size'] > 0) {
            $cover = upload('cover');

            if ($cover['code'] == 0) {
                $this->error($cover['msg']);
            }

            $data['cover'] = $cover['data'];
        }

        $result = $this->UserModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            if (!empty($data['cover']) && $_FILES['cover']['size'] > 0) {
                @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
            }

            if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
            }

            $this->error('修改失败');
        } else {
            if (!empty($data['cover']) && $_FILES['cover']['size'] > 0) {
                @is_file('.' . $user['cover']) && unlink('.' . $user['cover']);
            }

            if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                @is_file('.' . $user['avatar']) && unlink('.' . $user['avatar']);
            }

            $User = $this->UserModel->find($params['id']);
            $UserData = [
                'id' => $User['id'],
                'email' => $User['email'],
                'nickname' => $User['nickname'],
                'avatar' => $User['avatar_cdn'],
                'cover' => $User['cover_cdn'],
                'sex' => $User['sex'],
                'sex_text' => $User['sex_text'],
                'province' => $User['province'],
                'city' => $User['city'],
                'district' => $User['district'],
                'createtime' => $User['createtime'],
                'content' => $User['content'],
                'point' => $User['point'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
                'region' => $User['region_text']
            ];

            $this->success('修改成功', '/user/base/index', $UserData);
        }
    }

    //验证邮箱
    public function code()
    {
        $userid = $this->request->param('userid');
        $email = $this->request->param('email', '');
        $User = $this->UserModel->find($userid);

        if (!$User) {
            $this->error('该用户不存在');
        }

        $User = $this->UserModel->where(['email' => $email])->find();

        if (!$User) {
            $this->error("该邮箱不存在");
        }

        $code = build_rannum();

        session($User['id'], $code);

        // halt(session($User['id']));

        $content = "验证码：$code";

        $mail = new PHPMailer(true);


        //开启SMTP
        $mail->isSMTP(true);

        // 开启认证
        $mail->SMTPAuth = true;

        // SMTP服务器 163 => smtp.163.com
        $mail->Host = 'smtp.qq.com';

        //账号
        $mail->Username = '513104975@qq.com';

        //密码 => 不是邮箱密码 是开启smtp的授权码
        $mail->Password = 'asnelcxkkgdvbhcg';

        //端口 服务器需要开启465端口
        $mail->Port = 465;

        //协议
        $mail->SMTPSecure = 'ssl';

        //发件人邮箱
        $mail->From = '513104975@qq.com';

        //发件人名字
        $mail->FromName = 'ASK论坛';

        //接收回复的邮箱
        $mail->addReplyTo('513104975@qq.com', 'ASK论坛');

        //收件人
        $mail->addAddress($User['email'], $User['nickname']);

        //邮箱主题
        $mail->Subject = "账号认证";

        //设置多少个字符换行 80字符
        $mail->WordWrap = 80;

        //发送html的内容
        $mail->msgHTML($content);

        $result = $mail->send();

        if ($result === FALSE) {
            $this->error('发送邮件失败');
        } else {
            $this->success('发送邮件成功');
        }
    }

    //点击验证邮箱
    public function checkcode()
    {
        $userid = $this->request->param('userid');
        $code = $this->request->param('code');
        $User = $this->UserModel->find($userid);

        if (!$User) {
            $this->error('该用户不存在');
        }

        $check = session($User['id']);

        if ($check != $code) {
            $this->error('验证码错误');
        }

        $data = [
            'id' => $User['id'],
            'auth' => 1
        ];

        $result = $this->UserModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            $this->error('验证失败');
        } else {
            $this->success('验证成功');
        }
    }

    //充值积分
    public function topUpPoint()
    {
        $userid = $this->request->param('userid', 0);
        $sms = $this->request->param('sms', '');

        $User = $this->UserModel->find($userid);
        // halt($user);

        if (!$User) {
            $this->error('用户不存在');
        }

        $data = [
            'id' => $userid,
            'point' => bcadd($User['point'], $sms)
        ];
        $UserResult = $this->UserModel->isUpdate(true)->save($data);


        //新增消费记录
        $RecordData = [
            // 'id' => $RecordId + 1,
            'userid' => $userid,
            'point' => $sms,
            'createtime' => strtotime(date('Y-m-d H:i:s', time())),
            'content' => "您充值{$sms}积分，积分已经到账。",
            'state' => 3
        ];
        $RecordStatus = $this->RecordModel->validate('common/User/Record')->insert($RecordData);


        $UserData = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar' => $User['avatar_cdn'],
            'cover' => $User['cover_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $data['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'region' => $User['region_text']
        ];
        if ($UserResult === FALSE  || $RecordStatus === FALSE) {
            $this->error('充值失败');
        } else {
            $this->success('充值成功', null, $UserData);
        }
    }
}
